﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Xsl;

public partial class test_cache : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.RequestType == "GET")
        {
            if (Request.QueryString["action"] == "viewcache")
            {
                ViewCache();
            }
            else
            {
                PageQuery();
            }
        }
        else
        {
            string action = Request.QueryString["action"];
            if (string.IsNullOrEmpty(action))
            {
                Response.Redirect("cache.aspx");
            }
            if (action == "deleteruntimecache")
            {
                string[] cache = Request.Form.GetValues("cache");
                foreach (string c in cache)
                {
                    HttpRuntime.Cache.Remove(c);
                }
                Response.Redirect("cache.aspx");
            }
        }
    }

    private void ViewCache()
    {
        string key = Request.QueryString["key"];
        string type = Request.QueryString["type"];
        if (HttpRuntime.Cache[key] == null)
        {
            Response.ContentType = "text/html";
            Response.Write("缓存值为空（key=" + key + "）");
            Response.End();
            return;
        }
        if (type.Contains("XmlDocument"))
        {
            Response.ContentType = "text/xml";
            XmlDocument dom = (XmlDocument)HttpRuntime.Cache[key];
            dom.Save(Response.OutputStream);
            Response.End();
            return;
        }
        if (type.Contains("XslCompiledTransform"))
        {
            Response.ContentType = "text/xml";
            Response.WriteFile(key);
            Response.End();
            return;
        }
        
        if (type.Contains("Generic.List"))
        {
            if (key.EndsWith("primarykey.txt"))
            {
                Response.ContentType = "text/plain";
                Response.WriteFile(key);
                Response.End();
                return;
            }
        }
        
      
        if (type.Contains("Generic.Dictionary"))
        {
            if (type.Contains("[System.String,System.String]"))
            {
                StringBuilder sb = new StringBuilder();
                Dictionary<string, string> Dict = (Dictionary<string, string>)HttpRuntime.Cache[key];
                sb.Append("<table border='1'>");
                foreach (string item in Dict.Keys)
                {
                    string xml = Dict[item];
                    sb.AppendFormat("<tr><th>{0}</th><td>{1}</td></tr>", item, xml.StartsWith("<")&&xml.EndsWith(">")?HttpUtility.HtmlEncode(xml):xml);
                }
                sb.Append("</table>");
                Response.ContentType = "text/html";
                Response.Write(sb.ToString());
                Response.End();
                return;
            }
        }
        if (type.Contains("System.String"))
        {
            if (key.EndsWith(".xml"))
            {
                Response.ContentType = "text/xml";
                Response.WriteFile(key);
            }
            else
            {
                Response.ContentType = "text/html";
                Response.Write((String)HttpRuntime.Cache[key]);
            }
            Response.End();
            return;
        }
        if (type.Contains("System.Xml.Linq.XDocument"))
        {
            Response.ContentType = "text/xml";
            Response.Write(((System.Xml.Linq.XDocument)HttpRuntime.Cache[key]).ToString());
            Response.End();
            return;
        }
        Response.ContentType = "text/html";
        Response.Write("不能识别的类型（type=" + type + "）");
        return;
    }

    private void PageQuery()
    {
        Response.Write("Application Cache:<br />");
        StringBuilder sb = new StringBuilder();
        sb.Append("<table border='1' cellpadding='4' cellspacing='0'>");
        int counter = 1;
        foreach (string key in Application.AllKeys)
        {
            string type = Application[key].GetType().ToString();
            if (type.Length > 100)
            {
                type = type.Substring(0, 100) + "......";
            }
            sb.Append("<tr><td>" + (counter++) + "</td><td>" + key + "</td><td>" + type + "</td></tr>");
        }
        sb.Append("</table>");
        Response.Write(sb.ToString());

        sb.Remove(0, sb.Length);

        //AppEntity.RemoveAllXslCache();
        IDictionaryEnumerator CacheEnum = HttpRuntime.Cache.GetEnumerator();
        sb.Append("可用于缓存的字节数：<strong title='" + (HttpRuntime.Cache.EffectivePrivateBytesLimit / (1024 * 1024)) + "Mb'>" + HttpRuntime.Cache.EffectivePrivateBytesLimit + "</strong>，");
        sb.Append("可用于缓存的物理内存百分比：<strong>" + HttpRuntime.Cache.EffectivePercentagePhysicalMemoryLimit + "%</strong>");
        sb.Append("<script>function selectAll(cache){for(var i=0; i<cache.length; i++){cache[i].checked=true}}</script>");
        sb.Append("<form name='form2' method='post' action='?action=deleteruntimecache'>");
        sb.Append("<a href='javascript:void(0)' onclick='selectAll(document.form2.cache)'>全选</a> <button type='submit' style='margin-left:2em'>删除勾选的 HttpRuntime.Cache</button>");
        sb.Append("<br/>HttpRuntime.Cache:<br/><table border='1' cellpadding='4' cellspacing='0'>");
        int counter2 = 1;
        SortedDictionary<string, object> sst = new SortedDictionary<string, object>();
        while (CacheEnum.MoveNext())
        {
            sst.Add(CacheEnum.Key.ToString(), CacheEnum.Value);
        }
        foreach (KeyValuePair<string, object> key in sst)
        {
            sb.AppendFormat("<tr><td>{0}</td><td><input type='checkbox' name='cache' value='{1}'/></td><td>{1}</td><td>{2}</td><td><a href='?action=viewcache&key={3}&type={4}' target='_blank'>查看</a></td></tr>", counter2++, key.Key, key.Value.GetType(), HttpUtility.UrlEncode(key.Key), HttpUtility.UrlEncode(key.Value.GetType().ToString()));
        }
        sb.Append("</table>");
        sb.Append("<a href='javascript:void(0)' onclick='selectAll(document.form2.cache)'>全选</a> <button type='submit' style='margin-left:2em'>删除勾选的 HttpRuntime.Cache</button>");
        sb.Append("</form>");
        Response.Write(sb.ToString());

        StringBuilder appsb = new StringBuilder();
        foreach (string key in HttpContext.Current.Application.AllKeys)
        {
            appsb.Append(key + "<br/>");
        }
        Response.Write("<br/><br/><br/>" + appsb.ToString());


    }
}
